import json
from flask import jsonify, request, make_response, render_template
from . import web  # 从init中导入 web 蓝图
from app.forms.book import SearchForm
from app.libs.helper import is_isbn_or_key
from app.spider.yushu_book import YushuBook
from app.view_models.book import BookCollection


# 使用蓝图注册视图函数
@web.route('/book/search')
def search():
    '''
    q: 关键字搜索， isbn 搜索 ?q={}&page={}
    page
    '''
    # q = request.args['q']
    # page = request.args['page']
    form = SearchForm(request.args)  # 实例化验证

    if form.validate():  # 验证参数
        q = form.q.data
        page = form.page.data  # 若查询函数传递的参数是空，会从form中取默认值
        isbn_or_key = is_isbn_or_key(q)
        yushu_book = YushuBook()

        if isbn_or_key == 'isbn':
            yushu_book.search_by_isbn(q)
        else:
            yushu_book.search_by_keyword(q, page)

        # dict 序列化
        # 数据返回 api
        books = BookCollection()
        books.fill(yushu_book, q)
        # import pdb; pdb.set_trace()
        response = make_response(json.dumps(
            books, default=lambda o: o.__dict__))
        response.headers['Content-Type'] = 'application/json'
        return response
        # return json.dumps(result), 200, {'content-type': 'application/json'}
    else:
        return jsonify(form.errors)


@web.route('/test')
def test():
    r = {
        'name': 'jack',
        'age': 19
    }
    return render_template('test.html', r=r)
